﻿using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.DynamicsCRMGateway
{
    public static class TypeExtensions
    {
        private static readonly Dictionary<Type, string> EntityLogicalNames = new Dictionary<Type, string>();

        public static string GetEntityLogicalName(this Type type)
        {
            if (EntityLogicalNames.ContainsKey(type))
            {
                return EntityLogicalNames[type];
            }

            var entityLogicalNameAttribute = type.GetCustomAttributes(typeof(EntityLogicalNameAttribute), false).FirstOrDefault() as EntityLogicalNameAttribute;

            if (entityLogicalNameAttribute == null)
            {
                throw new InvalidOperationException("There is no EntityLogicalNameAttribute on the type " + type.Name);
            }

            string entityLogicalName = entityLogicalNameAttribute.LogicalName;
            EntityLogicalNames[type] = entityLogicalName;

            return entityLogicalName;
        }
    }
}
